import { useEffect, useRef } from 'react';
import * as echarts from 'echarts'; //全局引入 ，可按需引入
import china from '@/utils/china.json';
import { getFarmMachineProvince } from '@/services/api/home';
// import "./map.css";

const contentStyle: React.CSSProperties = {
  height: '500px',
  background: '#fff',
  borderRadius: '14px',
  marginTop: '18px',
};
interface ChartsProps {
  id?: any;
  option?: any;
  actionRef?: any;
}
const Map = (props: ChartsProps) => {
  const chartRef = useRef<any>(null);
  const getReqData = async () => {
    const res = await getFarmMachineProvince();
    let { result } = res;
    let target = [{ name: '南海诸岛', value: 0 }];
    china.features.forEach((item) => {
      let data;
      result.forEach((i: any) => {
        if (i.province === item.properties.name) {
          data = { name: i.province, value: i.machineNumbers };
        }
      });
      target.push(data ? data : { name: item.properties.name, value: 0 });
    });
    mapOption('china', china, target);
  };
  useEffect(() => {
    getReqData();
  }, []);
  var myChart: echarts.ECharts;
  const mapOption = (mapName: string, data: object, dataCount: any[]) => {
    myChart = echarts.init(chartRef.current);
    echarts.registerMap(mapName, data);
    var option: object = {
      title: {
        text: '所有车辆分布',
        left: 20,
        top: 26,
        textStyle: {
          fontSize: 22,
        },
      },
      tooltip: {
        trigger: 'item',
        formatter: '{c}辆',
      },
      visualMap: {
        min: 0,
        max: 100,
        text: ['高', '低'],
        realtime: false,
        calculable: false,
        orient: 'horizontal',
        inRange: {
          color: ['#e9f3fc', '#90bcf1', '#3885e2'],
        },
        itemWidth: 16,
        itemHeight: 50,
        left: 40,
        bottom: 62,
      },
      series: [
        {
          name: '中国地图',
          type: 'map',
          map: 'china',
          label: {
            show: true,
            formatter: '{c}',
          },
          data: dataCount,
          left: 34,
          top: 128,
          zoom: 1.1,
        },
      ],
    };
    myChart.setOption(option);
  };
  return <div style={contentStyle} ref={chartRef} />;
};
export default Map;
